import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import _ from 'lodash'
import { ElInput, ElMessage, ElNotification } from 'element-plus'
import VXBossApi from '@/api/vx-boss-api'
import { setZhiPinToken, removeAllCookies } from '@/utils/cookies'

export default {
  setup() {
    const InputRef = ref<InstanceType<typeof ElInput>>()

    const viewObj = reactive({
      stationId: '',
      stationIdList: [] as SelectorModel[],
      jobhunterArray: [] as Jobhunter[],
      ageRange: [18, 45],
      livenessList: [
        { label: '不限', value: 0 },
        { label: '刚刚活跃', value: 2501 },
        { label: '今天活跃', value: 2502 },
        { label: '3日内活跃', value: 2503 },
        { label: '本周活跃', value: 2504 },
        { label: '本月活跃', value: 2505 }
      ] as SelectorModel[],
      livenessSelected: [0],
      schoolLevelList: [
        { label: '不限', value: 0 },
        { label: '985', value: 1104 },
        { label: '211', value: 1103 },
        { label: '双一流院校', value: 1102 },
        { label: '留学', value: 1105 },
        { label: '国内外名校', value: 1106 },
        { label: '公办本科', value: 1107 }
      ] as SelectorModel[],
      schoolLevelSelected: [0],
      firstSchoolLevel: false,
      experienceRequireList: [
        { label: '不限', value: 0 },
        { label: '在校/应届', value: 109 },
        { label: '24年毕业', value: 110 },
        { label: '25年毕业', value: 111 },
        { label: '25年后毕业', value: 112 },
        { label: '1年以内', value: 103 },
        { label: '1-3年', value: 104 },
        { label: '3-5年', value: 105 },
        { label: '5-10年', value: 106 },
        { label: '10年以上', value: 107 }
      ] as SelectorModel[],
      experienceRequireSelected: [0],
      educationalRequireList: [
        { label: '不限', value: 0 },
        { label: '初中及以下', value: 209 },
        { label: '中专/中技', value: 208 },
        { label: '高中', value: 206 },
        { label: '大专', value: 202 },
        { label: '本科', value: 203 },
        { label: '硕士', value: 204 },
        { label: '博士', value: 205 }
      ] as SelectorModel[],
      educationalRequireSelected: [0],
      salaryRequireList: [
        { label: '不限', value: 0 },
        { label: '3k以下', value: 402 },
        { label: '3k-5k', value: 403 },
        { label: '5k-10k', value: 404 },
        { label: '10k-20k', value: 405 },
        { label: '20k-50k', value: 406 },
        { label: '50k以上', value: 407 }
      ] as SelectorModel[],
      salaryRequireSelected: [0],
      genderList: [
        { label: '不限', value: 0 },
        { label: '男', value: 2201 },
        { label: '女', value: 2202 }
      ] as SelectorModel[],
      genderSelected: [0],
      recentNotViewList: [
        { label: '不限', value: 0 },
        { label: '近14天没有', value: 2301 }
      ],
      recentNotViewSelected: [0],
      exchangeResumeWithColleagueList: [
        { label: '不限', value: 0 },
        { label: '近一个月没有', value: 1301 }
      ],
      exchangeResumeWithColleagueSelected: [0],
      switchJobFrequencyList: [
        { label: '不限', value: 0 },
        { label: '5年少于3份', value: 1201 },
        { label: '平均每份工作大于1年', value: 1202 }
      ],
      switchJobFrequencySelected: [0],
      intentionList: [
        { label: '不限', value: 0 },
        { label: '离职-随时到岗', value: 701 },
        { label: '在职-暂不考虑', value: 702 },
        { label: '在职-考虑机会', value: 703 },
        { label: '在职-月内到岗', value: 704 }
      ],
      intentionSelected: [0],
      elementTagTypes: ['primary', 'success', 'info', 'warning', 'danger'],
      authentication: '',
      loading: false,
      searchKeyword: {
        text: [] as string[],
        inputValue: '',
        isAddFocus: false,
        inputRef: ref<InstanceType<typeof ElInput>>(),
        inputHandleEnter: () => {
          if (_.trim(viewObj.searchKeyword.inputValue)) {
            viewObj.searchKeyword.text = Array.from(
              new Set(
                viewObj.searchKeyword.text.concat(
                  viewObj.searchKeyword.inputValue.split(/\s+/).filter(Boolean)
                )
              )
            )
          }

          viewObj.searchKeyword.inputValue = ''
        },
        inputHandleClose: () => {
          if (_.trim(viewObj.searchKeyword.inputValue)) {
            viewObj.searchKeyword.text = Array.from(
              new Set(
                viewObj.searchKeyword.text.concat(
                  viewObj.searchKeyword.inputValue.split(/\s+/).filter(Boolean)
                )
              )
            )
          }

          viewObj.searchKeyword.isAddFocus = false
          viewObj.searchKeyword.inputValue = ''
        },
        handleClose: (keyword: string) => {
          viewObj.searchKeyword.text.splice(viewObj.searchKeyword.text.indexOf(keyword), 1)
        },
        showInput: () => {
          viewObj.searchKeyword.isAddFocus = true
          nextTick(() => {
            InputRef.value!.input!.focus()
          })
        },
        cleanKeyword: () => {
          viewObj.searchKeyword.text.length = 0
        },
        copyKeyword: () => {
          navigator.clipboard
            .writeText(viewObj.searchKeyword.text.join(' '))
            .catch((e) => errorCallBack(e))
        }
      },
      pageNumber: 1,
      authorized: false,
      triggerChatUsed: 0,

      onQuery: () => {
        viewObj.jobhunterArray.length = 0
        viewObj.pageNumber = 1
        viewObj.loading = true
        loadData()
      },

      onLoadMore: () => {
        if (viewObj.loading) return
        viewObj.loading = true
        loadData()
      },

      ageRangeFormat: (value: number): string => value + '岁',

      replaceNewLinesWithBr: (text: string) => {
        const content = text.replace(/\n/g, '<br>')
        return viewObj.searchKeyword.text.length > 0 ? markHighlightText(content) : content
      },

      assembleTags: (labels: String[]): ElementTagModel[] => {
        return labels.map(
          (label, index) =>
            ({
              label: label,
              type: viewObj.elementTagTypes[index % viewObj.elementTagTypes.length]
            }) as ElementTagModel
        )
      },

      onChangeLiveness: (values: number[]) => {
        viewObj.livenessSelected =
          values.length === 0 || values[values.length - 1] === 0
            ? [0]
            : values.filter((i) => i !== 0)
      },

      onChangeSchoolLevel: (values: number[]) => {
        viewObj.schoolLevelSelected =
          values.length === 0 || values[values.length - 1] === 0
            ? [0]
            : values.filter((i) => i !== 0)
      },

      onChangeExperienceRequire: (values: number[]) => {
        viewObj.experienceRequireSelected =
          values.length === 0 || values[values.length - 1] === 0
            ? [0]
            : values.filter((i) => i !== 0)
      },

      onChangeEducationalRequire: (values: number[]) => {
        viewObj.educationalRequireSelected =
          values.length === 0 || values[values.length - 1] === 0
            ? [0]
            : values.filter((i) => i !== 0)
      },

      onChangeSalaryRequire: (values: number[]) => {
        viewObj.salaryRequireSelected =
          values.length === 0 || values[values.length - 1] === 0
            ? [0]
            : values.filter((i) => i !== 0)
      },

      onChangeIntention: (values: number[]) => {
        viewObj.intentionSelected =
          values.length === 0 || values[values.length - 1] === 0
            ? [0]
            : values.filter((i) => i !== 0)
      },

      onChangeGender: (values: number[]) => {
        viewObj.genderSelected = values.length === 0 ? [0] : [values[values.length - 1]]
      },

      onChangeRecentNotView: (values: number[]) => {
        viewObj.recentNotViewSelected = values.length === 0 ? [0] : [values[values.length - 1]]
      },

      onChangeExchangeResumeWithColleague: (values: number[]) => {
        viewObj.exchangeResumeWithColleagueSelected =
          values.length === 0 ? [0] : [values[values.length - 1]]
      },

      onChangeSwitchJobFrequency: (values: number[]) => {
        viewObj.switchJobFrequencySelected = values.length === 0 ? [0] : [values[values.length - 1]]
      },

      isMatchsearchKeyword: (content: string): boolean => {
        const keywords = viewObj.searchKeyword.text.map((keyword) => keyword.toLowerCase())
        return keywords.some((keyword) => content.includes(keyword))
      },

      onLogin: () => {
        viewObj.authorized = false
        setZhiPinToken(extractCookieValue(viewObj.authentication))
        login()
      },

      onTriggerChat: (index: number) => {
        if (!viewObj.stationId) {
          ElNotification({
            title: 'Error',
            message: '请先选择要筛选的岗位！',
            type: 'error',
            duration: 2000
          })
          return
        }
        VXBossApi.triggerChar(viewObj.jobhunterArray[index], viewObj.stationId).then(
          (res: ResultModel<String>) => {
            if (res.success && res.body != null) {
              viewObj.jobhunterArray[index].triggerChatFlag = true
              loadTriggerChatUsed()
              ElNotification({
                title: 'Success',
                message: '打招呼成功！',
                type: 'success',
                duration: 2000
              })
            } else {
              errorCallBack(res)
            }
          }
        )
      },

      isAuthorizedAndStationIdValid: (): boolean => viewObj.authorized && Boolean(viewObj.stationId)
    })

    onMounted(() => {
      removeAllCookies()
      viewObj.jobhunterArray = []
    })

    const scrollDisabled = computed<boolean>(() => viewObj.jobhunterArray.length === 0)

    return {
      viewObj,
      onMounted,
      scrollDisabled,
      InputRef
    }

    function errorCallBack(res: ResultModel<any>) {
      console.log('err' + res) // for debug
      ElNotification({
        title: 'Error',
        message: (res.body ? JSON.stringify(res.body) : res.message) || res.message,
        type: 'error',
        duration: 2000
      })
    }

    function extractCookieValue(curlCommand: string): string {
      const cookieHeaderRegex = /-H 'cookie: ([^']+)'/i
      const match = curlCommand.match(cookieHeaderRegex)
      return match && match[1] ? match[1] : extractCookieValue2(curlCommand)
    }

    function extractCookieValue2(curlCommand: string): string {
      const cookieHeaderRegex = /-b '([^']+)'/i
      const match = curlCommand.match(cookieHeaderRegex)
      return match && match[1] ? match[1] : ''
    }

    function markHighlightText(content: string): string {
      const keywords = viewObj.searchKeyword.text.map((keyword) => keyword.toLowerCase())
      const regex = new RegExp(`(${keywords.join('|')})`, 'gi')
      return content.replace(regex, (match) => `<span class="highlight">${match}</span>`)
    }

    function loadData() {
      VXBossApi.getJobhunterList(viewObj)
        .then((res: ResultModel<Jobhunter[]>) => {
          if (res.success && res.body != null) {
            viewObj.jobhunterArray = uniqueByProperty(
              [...viewObj.jobhunterArray, ...(res.body as [])],
              'jobhunterId'
            )
            viewObj.pageNumber = res.body[0].pageNumber
            viewObj.loading = false
          } else {
            errorCallBack(res)
          }
        })
        .finally(() => {
          viewObj.loading = false
        })
    }

    function uniqueByProperty(array: any[], key: string) {
      const seen = new Set()
      return array.filter((item) => {
        const k = item[key]
        return seen.has(k) ? false : seen.add(k)
      })
    }

    function login() {
      VXBossApi.getStationList().then((res: ResultModel<SelectorModel[]>) => {
        viewObj.stationIdList.length = 0
        if (res.success && res.body != null) {
          viewObj.authorized = true
          viewObj.stationIdList = [...res.body]
          viewObj.stationId = viewObj.stationIdList[0].value as string
          viewObj.jobhunterArray.length = 0
          loadTriggerChatUsed()
          ElMessage({
            message: '登陆成功',
            type: 'success'
          })
        } else {
          errorCallBack(res)
        }
      })
    }

    function loadTriggerChatUsed() {
      VXBossApi.getTriggerChatUsed().then((res: ResultModel<String>) => {
        viewObj.triggerChatUsed = 0
        if (res.success && res.body != null) {
          viewObj.triggerChatUsed = Number(res.body.match(/\d+/g)?.join('')) || 0
        } else {
          errorCallBack(res)
        }
      })
    }
  }
}
